package com.id.coinscleaner.utils

import android.app.ActivityManager
import android.content.Context
import android.text.format.Formatter
import com.id.coinscleaner.App.Companion.appContext
import java.util.regex.Pattern
import kotlin.math.ceil


/**
 * 获取已使用的运行内存
 * 单位GB
 */
fun getAvailMemory() = getMemory("availMem")

/**
 * 获取总运行内存
 * 单位GB
 */
fun getTotalMemory() = ceil(getMemory("totalMem").toDouble()).toFloat()

/**
 * 获取运行内存使用情况
 */
fun getMemoryUsage(): Float = (getAvailMemory() / getTotalMemory()) * 100

private fun getMemory(type: String): Float {
    val am = appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    val mi = ActivityManager.MemoryInfo()
    am.getMemoryInfo(mi)
    return try {
        if (type == "availMem") {
            Formatter.formatFileSize(appContext, mi.availMem)
        } else {
            Formatter.formatFileSize(appContext, mi.totalMem)
        }.run {
            val pattern = Pattern.compile("\\d+\\.\\d+")
            val matcher = pattern.matcher(this)
            matcher.find()
            matcher.group().toFloat()
        }
    } catch (e: Throwable) {
        0f
    }
}